package com.aqgj.User.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.aqgj.Organization.bean.Organization;
import com.aqgj.User.bean.UserVo;
import com.aqgj.User.bean.User;
import com.aqgj.User.dao.UserDao;
import com.aqgj.UserRole.bean.UserRole;
import com.aqgj.UserRole.dao.UserRoleDao;
import com.aqgj.common.BeanUtils;
import com.aqgj.util.Pager;
import com.aqgj.util.StringUtils;
import com.ztc.ZtcTransport.bean.ZtcTransport;
import com.ztc.ZtcWallet.bean.ZtcWallet;
import com.ztc.ZtcWallet.dao.ZtcWalletDao;
import com.ztc.ZtcTransport.dao.ZtcTransportDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service("User")
public class UserManager{

    @Autowired
    ZtcTransportDao ztcTransportDao;
    @Autowired
    UserDao userDao;
    @Autowired
    ZtcWalletDao ztcWalletDao;
    @Autowired
    UserRoleDao userRoleDao;

    private static final String DATE_FORMAT_FULL = "yyyy-MM-dd hh:mm:ss";


    public User findUserByAccount(String account){
        return userDao.findUniqueBy("account",account);
    }

    //获取当前公司全部用户
    public HashMap<String,Object> getUser(User user){
        HashMap<String,Object> result=new HashMap<>();
        ZtcTransport ztcTransport=ztcTransportDao.get(user.getTransportId());
        List<User> list=null;
        if(ztcTransport!=null&&"0".equals(String.valueOf(ztcTransport.getType()))){
            list=userDao.getAll();
        }else{
            list=userDao.findBy("transportId",user.getTransportId());
        }
        List<HashMap<String,Object>> lists=new ArrayList<>();
        HashMap<String,Object> map=null;
        for (User u:list) {
            map=new HashMap<>();
            map.put("id",u.getId());
            map.put("account",u.getAccount());
            map.put("name",u.getName());
            map.put("org",u.getTransportId()!=null?ztcTransportDao.get(u.getTransportId()).getFullName():"");
            map.put("status",getUserStatus(u.getStatus()));
            map.put("uStatus",u.getStatus());
            map.put("tel",u.getTelPhone());
            map.put("currTime",new SimpleDateFormat(DATE_FORMAT_FULL).format(u.getCurrTime()));
            lists.add(map);
        }
        result.put("Rows",lists);
        return result;
    }

    public String save(User user){
        userDao.save(user);
        return user.getId();
    }

    public String update(User user){
        userDao.update(user);
        return user.getId();
    }

    public User get(String id){  return userDao.get(id); }

    public User findUniqueBy(String propertyName,Object value){ return userDao.findUniqueBy(propertyName,value); }

    public void removeById(String id){ userDao.removeById(id); }

    public List<User> findBy(String propertyName,Object value){ return userDao.findBy(propertyName,value); }

    @Transactional
    public void saveRegisterUser(User user){
        User user1 = userDao.findUniqueBy("telPhone",user.getTelPhone());
        if(user1!=null){
            throw new RuntimeException("手机号码已存在");
        }
        user.setCurrTime(new Date());
        user.setStatus("1");
        userDao.save(user);
        if(user.getId()!=null && !"".equals(user.getId())){
            ZtcWallet ztcWallet = new ZtcWallet();
            ztcWallet.setFkUserId(user.getId());
            if(ztcWalletDao.findUniqueBy("fkUserId",user.getId())!=null){
                throw new RuntimeException("用户钱包已存在");
            }
            ztcWalletDao.save(ztcWallet);
            if(ztcWallet.getId()==null || "".equals(ztcWallet.getId())){
                throw new RuntimeException("注册失败，请重试");
            }
        }
    }

    //用户状态
    private String getUserStatus(String status) {
        String temp = "";
        switch (status) {
            case "1":temp = "正常";break;
            case "2":temp = "账号冻结";break;
        }
        return temp;
    }

    public List<User> selectByLoginName(UserVo userVo) {
        return userDao.findBy("account",userVo.getAccount());
    }

    public void insertByVo(UserVo userVo,String tid) {
        User user = BeanUtils.copy(userVo, User.class);
        user.setCurrTime(new Date());
        user.setTransportId(tid);
        Organization organization = new Organization();
        organization.setId(userVo.getOrganizationId());
        user.setOrganization(organization);
        userDao.save(user);

        String id = user.getId();
        JSONArray roles = JSON.parseArray(userVo.getRoleIds());
        UserRole userRole = null;
        for (Object string : roles) {
            userRole = new UserRole();
            userRole.setUserId(id);
            userRole.setRoleId(string.toString());
            userRoleDao.save(userRole);
        }
    }

    public User selectById(String id) {
        return userDao.selectUserById(id);
    }

    public void updateByVo(UserVo userVo) {
        User user = BeanUtils.copy(userVo, User.class);
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        }

        int count = userDao.updateUser(user);
        String id = userVo.getId();
        List<UserRole> userRoles = userRoleDao.findBy("userId",id);
        if (userRoles != null && !userRoles.isEmpty()) {
            for (UserRole userRole : userRoles) {
                userRoleDao.removeById(userRole.getId());
            }
        }

        JSONArray roles = JSON.parseArray(userVo.getRoleIds());
        UserRole userRole = new UserRole();
        for (Object string : roles) {
            userRole.setUserId(id);
            userRole.setRoleId(string.toString());
            userRoleDao.save(userRole);
        }
    }

    public void updatePwdByUserId(String userId, String md5Hex) {
        User user = new User();
        user.setId(userId);
        user.setPassword(md5Hex);
        userDao.save(user);
    }

    public Pager<User> selectDataGrid(UserVo userVo,Integer pageSize, Integer pageNumber) {
//        if(userVo.getOrganizationId() != null){
//            return userDao.findBy("organization",userVo.getOrganizationId());
//        }else if(userVo.getName()!=null){
//            return userDao.findBy("name",userVo.getName());
//        } else{
//            return userDao.getAll();
//        }
        return userDao.selectDataGrid(userVo,pageSize,pageNumber);
    }

    public void deleteUserById(String id) {
        userDao.removeById(id);
        userRoleDao.deleteByUserId(id);
    }

    public User selectUserById(String id){
        return userDao.get(id);
    }

}
